from info import sr
from info.constants import HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.utils.response_code import RET, error_map
from . import home_blu
from flask import render_template, current_app, session, request, jsonify, abort


# 2.使用蓝图对象来注册路由
@home_blu.route('/')
def index():
    # 判断用户是否登录  取出session中的user_id
    user_id = session.get("user_id")
    user = None  # type: User
    if user_id:  # 已登录
        # 查询用户数据
        try:
           user = User.query.get(user_id)
        except BaseException as e:
            current_app.logger.error(e)

    # 按照点击量查询排行前10的新闻数据
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)

    news_list = [news.to_basic_dict() for news in news_list]

    # 查询所有的分类数据, 传入模板
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    # 转换用户数据
    user = user.to_dict() if user else None

    # 将用户数据传入模板
    return render_template("news/index.html", user=user, news_list=news_list, categories=categories)



# 设置网站小图标
@home_blu.route('/favicon.ico')
def favicon():
    # /favicon.ico请求是由浏览器自动发起的, 网站只要实现该路由, 返回图片即可

    # 可以使用flask中内置的语法app.send_static_file()来返回静态文件
    return current_app.send_static_file("news/favicon.ico")


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get("cid")
    cur_page = request.args.get("cur_page")
    per_count = request.args.get("per_count", HOME_PAGE_MAX_NEWS)
    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    
    # 格式转换
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 新闻必须审核通过才能显示
    filter_list = [News.status == 0]
    # 判断分类是否为"最新"
    if cid != 1:
        filter_list.append(News.category_id == cid)

    # 按照分类和页码获取新闻数据   发布时间倒序
    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 包装到json中返回
    data = {
        "news_list": [news.to_dict() for news in pn.items],
        "total_page": pn.pages
    }
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)